<template>
  <div>
    <el-dialog v-model="dialogFormVisible" title="编辑商铺">
      <el-form :model="form">
        <el-form-item label="商铺名称" label-width="140px">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商铺介绍" label-width="140px">
          <el-input v-model="form.introduce" autocomplete="off" type="textarea" />
        </el-form-item>

        <el-form-item label="状态" label-width="140px">
          <el-select v-model="form.state" placeholder="请选择店铺状态">
            <el-option
              v-for="(item, index) in optionList"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片" label-width="140px">
          <el-upload
            v-model:file-list="form.img"
            action="/api/upload/img"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="hanleSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <el-dialog v-model="photoShowFlag">
        <img :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="Edit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-backtop :right="100" :bottom="100" />
    <el-dialog title="新增商铺" v-model="ShopDialogFormVisible">
      <el-form :model="insert">
        <el-form-item label="店铺名称" label-width="140px">
          <el-input v-model="insert.name" placeholder="请输入店铺名称"></el-input>
        </el-form-item>
        <el-form-item label="店铺主" label-width="140px">
          <el-select v-model="insert.userId" placeholder="请选择店铺主">
            <el-option
              v-for="(item, index) in UserList"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺简介" label-width="140px">
          <el-input
            v-model="insert.introduce"
            placeholder="请输入店铺简介"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ShopDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="insertAll"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manager/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/manager/shop">店铺信息</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="header">
      <div style="width: 200px">
        <el-input v-model="input" placeholder="请输入搜索内容" />
      </div>
      <el-button type="primary" @click="search">搜索</el-button>
    </div>
    <div class="insert">
      <el-button type="info" size="large" @click="ChooseIF" style="margin-right: 50px"
        >新增商铺</el-button
      >
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="商铺名称">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-icon><timer /></el-icon>
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="简介">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top">
            <template #default>
              <div>{{ scope.row.introduce }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.introduce }} </el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="店铺主" prop="userId"> </el-table-column>
      <el-table-column label="入驻时间" prop="inputTime" width="200px"></el-table-column>
      <el-table-column label="Operations">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageSize"
      v-model:page-size="pageItem"
      :page-sizes="[20, 30, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="ItemTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ref, reactive } from "vue";
import { Timer, Message } from "@element-plus/icons-vue";
import { el } from "element-plus/es/locale";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";

const optionList = ref([
  {
    label: "正常",
    value: 1,
  },
  {
    label: "关闭",
    value: 0,
  },
]);

const UserList = ref([]);

const ShopDialogFormVisible = ref(false);

const Edit = () => {
  console.log(form);
  console.log(form.state);

  axios
    .post("/api/shop/update", {
      shopId: form.id,
      name: form.name,
      img: JSON.stringify(form.img),
      introduce: form.introduce,
      state: form.state,
    })
    .then((res) => {
      console.log(res);
      if (res.data.success) {
        ElMessage({
          message: "更新成功",
          type: "success",
        });
      } else {
        ElMessage({
          message: "更新失败",
          type: "error",
        });
        search();
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    dialogFormVisible.value = false;
  }, 200);
};

// const fileList = ref<UploadUserFile[]>([]);

const dialogFormVisible = ref(false);
const photoShowFlag = ref(false);
const dialogImageUrl = ref("");

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  console.log(res);
  // form.img.push({
  //   name: res.message,
  //   url: res.message,
  // });
  console.log(form.img);
  console.log(form.img.length);
  let arr = [];
  for (let i = 0; i < form.img.length - 1; i++) {
    const element = form.img[i];

    arr.push({
      name: element.name,
      url: element.url,
    });
  }
  arr.push({
    name: res.message,
    url: res.message,
  });
  form.img = arr;

  console.log(JSON.stringify(form.img));
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  photoShowFlag.value = true;
};

interface Shop {
  name: string;
  introduce: string;
  inputTime: Date;
  userId: string;
  shopId: string;
  img: string;
  updateTime: Date;
  state: number;
}
const insert = reactive({
  name: "",
  introduce: "",
  userId: "",
});

const insertAll = () => {
  axios
    .post("/api/shop/insert", {
      name: insert.name,
      introduce: insert.introduce,
      userId: insert.userId,
    })
    .then((res) => {
      console.log(res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "新建成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: res.data.message,
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    insert.name = "";
    insert.userId = "";
    insert.introduce = "";
    ShopDialogFormVisible.value = false;
    search();
  }, 200);
};

const form = reactive({
  id: "",
  name: "",
  introduce: "",
  img: ref<UploadUserFile[]>([]),
  state: 1,
});
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  search();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  search();
};

const handleEdit = (index: number, row: Shop) => {
  form.id = row.shopId;
  form.name = "";
  form.introduce = "";
  form.img = [];
  form.state = 1;

  axios
    .get("/api/shop/g/" + row.shopId)
    .then((res) => {
      console.log(res);
      form.name = res.data.message.name;
      form.introduce = res.data.message.introduce;
      form.state = res.data.message.state;
      if (res.data.message.img != "" && res.data.message.img != undefined) {
        form.img = JSON.parse(res.data.message.img);
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    dialogFormVisible.value = true;
    console.log(index, row);
  }, 300);
};
const handleDelete = (index: number, row: Shop) => {
  console.log(index, row);
  console.log(row);

  ElMessageBox.confirm("是否删除该商品" + row.name, "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .get("/api/shop/del?id=" + row.shopId)
        .then((res) => {
          console.log(res);
          if (res.data.success) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          } else {
            ElMessage({
              type: "error",
              message: res.data.message,
            });
          }
          search();
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const tableData = ref([]);

const input = ref("");
const pageSize = ref(1);
const pageItem = ref(20);
const PageTotal = ref(0);
const ItemTotal = ref(0);
const search = () => {
  axios
    .get(
      "/api/shop/get/" + pageSize.value + "/" + pageItem.value + "?name=" + input.value
    )
    .then((res) => {
      console.log(res);
      const msg = res.data.message.list;
      console.log(msg);
      msg.forEach((element) => {
        if (element.img != null) {
          element.img = JSON.parse(element.img);
        }
      });
      tableData.value = msg;
      console.log(tableData.value);
      PageTotal.value = res.data.message.pages;
      ItemTotal.value = res.data.message.total;
    })
    .catch((err) => {
      console.log(err);
    });
};
const ChooseIF = () => {
  getUserInfo();
  ShopDialogFormVisible.value = true;
};
const getUserInfo = () => {
  axios
    .get("/api/user/options")
    .then((res) => {
      console.log(res);
      UserList.value = res.data.message;
    })
    .catch((err) => {});
};

search();
</script>

<style lang="scss" scoped>
.header {
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.insert {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
